package atech.ace.mapping;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import atech.ace.mapping.persistence.entities.HumanResource;

/**
 * Servlet implementation class Create
 */
@WebServlet("/Create")
public class Create extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@PersistenceContext(name="jdbc/ACE_ProjectMapping")
	EntityManager em;
	
	@Resource
	UserTransaction utx;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		setAttributes(request);
		request.getRequestDispatcher("WEB-INF/create.jsp").forward(request, response);
	}

	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		setAttributes(request);
		request.getRequestDispatcher("WEB-INF/create.jsp").forward(request, response);
	}
	
	private void setAttributes(HttpServletRequest request) {
		try {
			utx.begin();
			List resources = em.createQuery("select r from HumanResource r")
					.getResultList();
			List companies = em.createQuery("select c from Company c")
					.getResultList();
			List projects = em.createQuery("select p from Project p")
					.getResultList();
			request.setAttribute("resources", resources);
			request.setAttribute("companies", companies);
			request.setAttribute("projects", projects);
			utx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				utx.rollback();
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (SystemException e1) {
				e1.printStackTrace();
			}
		}
	

	}
	
	

}
